﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace XCommunity.Web
{

  /// <summary>
  /// 维护当前登录和未登陆账户信息的上下文
  /// </summary>
  public sealed class AccountContext
  {
    private Account _account;

    private const string CookieName = "XCommunity.AccountContext.AccountToken";


    private WebAccountService _service;

    private HttpContext _context;


    internal static AccountContext Create( HttpContext context )
    {
      AccountContext instance = new AccountContext( context );
      context.Items[typeof( AccountContext )] = instance;

      return instance;
    }


    private AccountContext( HttpContext context )
    {
      _service = WebCommunityContext.Current.AccountService;
      _context = context;
    }


    internal void CoockiesInit()
    {
      HttpCookie cookie = _context.Request.Cookies[CookieName];

      if ( cookie != null && !string.IsNullOrEmpty( cookie.Value ) )
      {

        var token = cookie.Value;

        GetAccount( token );

      }
      else
      {
        _account = GuestAccount.Create();

        _cookieContext = new HttpCookie( CookieName, _account.Token );
      }

    }


    internal void CookiesWrite()
    {
      if ( _cookieContext != null )
        _context.Response.Cookies.Set( _cookieContext );
    }



    private void GetAccount( string token )
    {
      _account = _service.GetAccount( token );

      if ( _account == null && token.EndsWith( "%" ) )
      {
        _account = GuestAccount.Create( token );
        _service.AddAccount( _account );
      }
    }



    public static AccountContext Current
    {
      get
      {
        if ( HttpContext.Current == null )
          throw new InvalidOperationException();

        return HttpContext.Current.Items[typeof( AccountContext )] as AccountContext;
      }
    }

    public static Account CurrentAccount
    {
      get { return Current.Account; }
    }


    private HttpCookie _cookieContext = null;


    internal void SignIn( Account account )
    {

      if ( !account.IsAuthenticated )
        throw new InvalidOperationException();//UNDONE 异常详细信息

      _service.AddAccount( account );
      _account = account;

      _cookieContext = new HttpCookie( CookieName, account.Token );
    }

    internal void SignOut()
    {

      if ( !_account.IsAuthenticated )
        return;

      _cookieContext = new HttpCookie( CookieName, GuestAccount.Create().Token );
    }

    public Account Account
    {
      get { return _account; }
    }

  }
}
